package com.biscuit.page.basicservice.utils;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.Map;

/**
 * @author mazihao
 * @createTime 2024/3/29 10:43
 */
@Slf4j
public class HttpUtil {

    private final static HttpClient HTTP_CLIENT = HttpClients.createDefault();

    public static <T> T get(String url, Map<String, String> paramMap, Class<T> clazz) {
        try {
            StringBuilder params = new StringBuilder();
            paramMap.forEach((key, value) -> params.append(key).append("=").append(value).append("&"));
            if (StringUtils.isNotBlank(params)) {
                url += "?" + params.substring(0, params.length() - 1);
            }
            return get(url, clazz);
        } catch (Exception e) {
            log.error("HttpClient GET 请求失败，失败原因 -> {}", e.getMessage());
        }
        return null;
    }

    public static String get(String url, Map<String, String> paramMap) {
        try {
            StringBuilder params = new StringBuilder();
            paramMap.forEach((key, value) -> params.append(key).append("=").append(value).append("&"));
            if (StringUtils.isNotBlank(params)) {
                url += "?" + params.substring(0, params.length() - 1);
            }
            return get(url);
        } catch (Exception e) {
            log.error("HttpClient GET 请求失败，失败原因 -> {}", e.getMessage());
        }
        return null;
    }

    private static <T> T get(String url, Class<T> clazz) throws IOException {
        String responseJson = get(url);
        if (StringUtils.isNotBlank(responseJson)) {
            return JSON.parseObject(responseJson, clazz);
        }
        return null;
    }

    private static String get(String url) throws IOException {
        HttpGet request = new HttpGet(url);
        setHeader(request);
        HttpResponse response = HTTP_CLIENT.execute(request);
        String responseJson = EntityUtils.toString(response.getEntity());
        if (StringUtils.isNotBlank(responseJson)) {
            return responseJson;
        }
        return null;
    }

    private static void setHeader(HttpUriRequest request) {
        request.setHeader("User-Agent", "Mozilla/5.0");
        request.setHeader("Accept", "application/json");
        request.setHeader("Accept-Language", "en-US");
        request.setHeader("Content-Type", "application/json");
    }

}
